03. Using Browser-Sync

Using Browsersync

Before we install Browsersync, we'll set up a watch task to the "default" task. This allows Gulp to keep an eye out for anything that changes in our code.

1. Add a watch task

Open up the gulpfile.js you'd worked with previously. Go ahead and modify your "default" task to look like the following:

gulp.task("default", ["styles"], function() {
  gulp.watch("sass/**/*.scss", ["styles"]);
});

So what did we just change? First, we passed in ["styles"]as the next argument into task(). We then added the expression gulp.watch("sass/**/*.scss", ["styles"]); into the body of function. As a result, if any changes are made to any .scss file(s) in our sass folder (and in its sub-folders), the "styles" function that we previously created will be run automatically!

2. Install browser-sync Locally

Next, enter the following expression in your terminal (again, make sure you're in the root directory of the project):

npm install browser-sync

After it has been successfully installed in your project, open up gulpfile.js and add the following:

const browserSync = require('browser-sync').create();

**3. Update the "default" Task **

In the body of the function run in the "default" task, add the following code:

browserSync.init({
  server: "./"
});

In the above code, calling .init on browserSync starts the server.

4. Update the "styles" Function

Finally, add the following line to the very bottom of the "styles" function:

.pipe(browserSync.stream());

Using a stream, we can reload at specific points during our tasks, and the browser will be informed of the changes. However, reloading before the CSS is done compiling wouldn't make sense (i.e., Gulp isn't transpiling the code) -- which is why it is important to integrate this line of code only when everything else is complete.

5. Run the "default" Task

Finally, go ahead and run the "default" task by running gulp in the terminal. Modify an .scss file or two. What happens in your browser?

How Are Things Looking?

After all the updates up to this point, your code in gulpfile.js should look something like this:

const gulp = require("gulp");
const sass = require("gulp-sass");
const autoprefixer = require("gulp-autoprefixer");
const browserSync = require("browser-sync").create();

gulp.task("default", ["styles"], function() {
  gulp.watch("sass/**/*.scss", ["styles"]);

  browserSync.init({
    server: "./"
  });
});

gulp.task("styles", function() {
  gulp
    .src("sass/**/*.scss")
    .pipe(sass().on("error", sass.logError))
    .pipe(
      autoprefixer({
        browsers: ["last 2 versions"]
      })
    )
    .pipe(gulp.dest("./css"))
    .pipe(browserSync.stream());
});

Alternatively, feel free to check out the course code here as well. Note that if you've already downloaded the ud892 course repository previously, the code in this lesson pertains to the Lesson 3 folder.